﻿from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from ckeditor.fields import RichTextField


class Tag(models.Model):
    name = models.CharField(max_length=50, unique=True, verbose_name="标签名称")
    description = models.TextField(blank=True, null=True, verbose_name="描述")
    is_active = models.BooleanField(default=True, verbose_name="是否启用")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="创建者")
    usage_count = models.PositiveIntegerField(default=0, verbose_name="使用次数")
    
    class Meta:
        verbose_name = "标签"
        verbose_name_plural = "标签管理"
        ordering = ["-created_at"]
    
    def __str__(self):
        return self.name


class Article(models.Model):
    STATUS_CHOICES = (
        ('draft', '草稿'),
        ('published', '已发布'),
        ('offline', '已下架'),
    )
    
    title = models.CharField(max_length=200, unique=True, verbose_name="文章标题")
    slug = models.SlugField(max_length=250, unique_for_date='publish_date', verbose_name="URL别名")
    summary = models.TextField(max_length=500, blank=True, null=True, verbose_name="内容摘要")
    content = RichTextField(verbose_name="文章内容")
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft', verbose_name="状态")
    publish_date = models.DateTimeField(blank=True, null=True, verbose_name="发布时间")
    view_count = models.PositiveIntegerField(default=0, verbose_name="阅读量")
    is_sticky = models.BooleanField(default=False, verbose_name="是否置顶")
    tags = models.ManyToManyField(Tag, related_name='articles', blank=True, verbose_name="标签")
    
    # SEO字段
    meta_title = models.CharField(max_length=200, blank=True, null=True, verbose_name="SEO标题")
    meta_description = models.TextField(max_length=255, blank=True, null=True, verbose_name="Meta描述")
    meta_keywords = models.CharField(max_length=255, blank=True, null=True, verbose_name="Meta关键词")
    
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="创建者")
    
    class Meta:
        verbose_name = "文章"
        verbose_name_plural = "文章管理"
        ordering = ["-is_sticky", "-publish_date", "-created_at"]
    
    def __str__(self):
        return self.title
    
    def save(self, *args, **kwargs):
        # 如果发布文章且发布时间为空，则设置为当前时间
        if self.status == 'published' and not self.publish_date:
            self.publish_date = timezone.now()
        # 如果下架文章，则清空发布时间
        elif self.status == 'offline':
            self.publish_date = None
        super().save(*args, **kwargs)
